package cn.com.dhc.danlu.activity.coupon;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.base.DanluTabFragmentActivity;
import cn.com.dhc.danlu.activity.base.WebViewActivity;
import cn.com.dhc.danlu.activity.coupon.callback.OnEnvelopLogicCallback;
import cn.com.dhc.danlu.constant.UrlConst;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.TipCountUtil;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DLToolbar;
import cn.com.hd.mall.web.webservices.entity.freedom.entity.coupon.CouponEntity;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetCouponListWithDealerReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.base.BaseResponseWrapper;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetCouponListWithDealerResponse;
import rx.Subscription;
import rx.functions.Action1;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-09-27
 * Time: 16:23
 * Description: 使用经销商红包界面实现 控制计算逻辑放置于当前activity中 fragment以及adapter不参与
 */
public class UseDealersEnvelopActivity extends DanluTabFragmentActivity implements OnEnvelopLogicCallback {

    public static final int USE_DEALER_ENVELOP_REQ = 0X111;

    private final List<CouponEntity> mLastSelects = new ArrayList<>();
    private String mDealerId;
    private int maxUse;
    private BigDecimal mMaxDeduction; // 单位分
    private String mTotalAmt; //经销商下所有商品总额(扣除满减满赠后)单位：分

    private Subscription mSubscription;
    private TextView tvDeduction;
    private TextView tvHasUsed;

    /**
     * 跳转使用经销商红包界面
     *
     * @param context          上下文
     * @param lastSelects      上次选在的数据 json 数据格式
     * @param dealerId         经销商ID
     * @param highestDeduction 最高抵扣金额
     * @param totalAmt         经销商下所有商品总额(扣除满减满赠后)单位：分
     * @param maxUse           张数限制
     */
    public static void startSelf(Activity context, String lastSelects, String dealerId, String highestDeduction, String totalAmt, int maxUse) {
        Intent intent = new Intent(context, UseDealersEnvelopActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("maxUse", maxUse);
        bundle.putString("totalAmt", totalAmt);
        bundle.putString("dealerId", dealerId);
        bundle.putString("lastSelects", lastSelects);
        bundle.putString("highestDeduction", highestDeduction);
        intent.putExtras(bundle);
        context.startActivityForResult(intent, USE_DEALER_ENVELOP_REQ);
    }

    @Override
    public void onSelected(CouponEntity entity, ImageView iv_check) {
        boolean isChoose = entity.isChecked(); // false -> 当前未选中 ready select
        if (isChoose) {
            // 从数组中移除指定的红包
            mLastSelects.remove(entity);
            //重新计算实际使用金额
            BigDecimal totalUseEvelop = getTotalUseEvelop();
            int compare = CalculatePriceUtil.compare(totalUseEvelop.toPlainString(), mMaxDeduction.toPlainString());
            String couponAmt = entity.getCouponAmt();
            for (CouponEntity model : mLastSelects) {
                if (CalculatePriceUtil.compare(model.getFactUse(), model.getCouponAmt()) != 0) {
                    BigDecimal addition = CalculatePriceUtil.addition(model.getFactUse(), couponAmt);
                    if (compare == -1 || compare == 0) {
                        // 小于|等于
                        model.setFactUse(model.getCouponAmt());
                    } else {
                        // + 补差价（去掉的）
                        model.setFactUse(addition.toPlainString());
                    }
                    break;
                }
            }
            entity.setIsChecked(false);
            iv_check.setImageResource(R.drawable.icon_envelop_checkpress);
        } else {
            // 控制逻辑 & 刷新逻辑
            // 判断使用张数是否超过最大
            // 是否超过最大抵扣金额
            if (mLastSelects.size() >= maxUse) {
                ToastUtil.getInstance().show("使用红包张数不能超过" + maxUse);
                return;
            }
            int compare = CalculatePriceUtil.compare(getTotalUseEvelop().toPlainString(), mMaxDeduction.toPlainString());
            if (compare == 1 || compare == 0) {
                //  之前选择的总金额大于最大使用量
                String maxYuan = CalculatePriceUtil.converseAmount(CommonUtils.fenToYuan(mMaxDeduction).toPlainString());
                ToastUtil.getInstance().show(getResources().getString(R.string.dl_beyond_dealer_envelop));
                return;
            }
            BigDecimal extraAdd = CalculatePriceUtil.addition(getTotalUseEvelop().toPlainString(), entity.getCouponAmt());
            int compare2 = CalculatePriceUtil.compare(extraAdd.toPlainString(), mMaxDeduction.toPlainString());
            if (compare2 == 1) {
                // 红包面额大于最大金额
                BigDecimal vacancyBd = CalculatePriceUtil.subtraction(extraAdd.toPlainString(), mMaxDeduction.toPlainString());
                BigDecimal useBd = CalculatePriceUtil.subtraction(entity.getCouponAmt(), vacancyBd.toPlainString());
                entity.setFactUse(useBd.toPlainString());
            } else {
                entity.setFactUse(entity.getCouponAmt());
            }
            mLastSelects.add(entity);
            entity.setIsChecked(true);
            iv_check.setImageResource(R.drawable.icon_envelop_checknormal);
        }
        refreshBottomView();
    }

    private BigDecimal getTotalUseEvelop() {
        BigDecimal bdTotal = new BigDecimal(0);
        for (int i = 0; i < mLastSelects.size(); i++) {
            bdTotal = CalculatePriceUtil.addition(bdTotal.toPlainString(), mLastSelects.get(i).getCouponAmt());
        }
        return bdTotal;
    }

    @SuppressLint("SetTextI18n")
    private void refreshBottomView() {
        BigDecimal deductionBd = CommonUtils.fenToYuan(getTotalUseEvelop());
        tvHasUsed.setText("¥" + CommonUtils.formateRate(deductionBd.toPlainString()));
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dl_activity_dealers_envelopuse);
        initCusView();
        getDataFromPrevious();
        // 刷新最高抵扣
        String yuanStr = CommonUtils.fenToYuan(mMaxDeduction).toPlainString();
        tvDeduction.setText("¥" + CalculatePriceUtil.converseAmount(yuanStr));
        // 刷新当前抵扣
        refreshBottomView();
        fetchCouponList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mSubscription && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

    private void initCusView() {
        tvDeduction = (TextView) findViewById(R.id.tv_deduction);
        tvHasUsed = (TextView) findViewById(R.id.tv_has_used);
        findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitAction();
            }
        });
        ((DLToolbar) findViewById(R.id.toolbar)).setRightClickListenter(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.startSelf(UseDealersEnvelopActivity.this, CommonUtils.getStringByResId(R.string.dl_title_desc_envelop), UrlConst.URL_DEALER_ENVELOP, false);
            }
        });
    }

    private void getDataFromPrevious() {
        Bundle bundle = getIntent().getExtras();
        String lastJson = bundle.getString("lastSelects");
        if (!TextUtils.isEmpty(lastJson)) {
            List<CouponEntity> lists = null;
            try {
                lists = CommonUtils.fromJsonArray(lastJson, CouponEntity.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLastSelects.addAll(lists);
        }
        mDealerId = bundle.getString("dealerId");
        maxUse = bundle.getInt("maxUse");
        String mdStr = bundle.getString("highestDeduction");
        mMaxDeduction = new BigDecimal(mdStr);
        mTotalAmt = bundle.getString("totalAmt");
    }

    @Override
    public void fetchCouponList() {
        String token = agent.getToken();
        agent.getApi()
                .getCouponListWithDealer(new GetCouponListWithDealerReq(token, mDealerId, mTotalAmt))
                .doOnNext(new Action1<BaseResponseWrapper<GetCouponListWithDealerResponse>>() {
                    @Override
                    public void call(BaseResponseWrapper<GetCouponListWithDealerResponse> wrapper) {
                        GetCouponListWithDealerResponse model = wrapper.getModel();
                        List<CouponEntity> couponList = model.getUseableCouponList();
                        if (null != couponList && !couponList.isEmpty() && !mLastSelects.isEmpty()) {
                            for (Object obj : mLastSelects) {
                                for (CouponEntity entity : couponList) {
                                    if (entity.equals(obj)) {
                                        entity.setIsChecked(true);
                                    }
                                }
                            }
                        }
                        boolean isMainUI = Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
                        Log.w("@@@@ L229", "UseDealersEnvelopActivity:call() -> " + "isMainUIThread = " + isMainUI);
                    }
                })
                .compose(OperatorUtils.<GetCouponListWithDealerResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetCouponListWithDealerResponse>() {
                    @Override
                    protected void onSuccess(GetCouponListWithDealerResponse model) {
                        refreshInnerFragment(null, model);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        refreshInnerFragment(displayMessage, null);
                    }
                });
    }

    /**
     * 确定
     */
    private void commitAction() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("selectJsonStr", CommonUtils.parseBean2Json(mLastSelects));
        bundle.putString("dealerId", mDealerId);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void refreshInnerFragment(String msg, GetCouponListWithDealerResponse datas) {
        for (int i = 0; i < 2; i++) {
            String tag = "android:switcher:" + mViewPager.getId() + ":" + i;
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
            if (null != fragment) {
                CouponableFragment cf = (CouponableFragment) fragment;
                if (null != msg) {
                    cf.showErrorView(msg);
                } else {
                    if (i == 0) {
                        List<CouponEntity> useableCouponList = datas.getUseableCouponList();
                        if (null == useableCouponList) {
                            useableCouponList = new ArrayList<>();
                        }
                        updateTitle(i, "可用红包(" + TipCountUtil.cover(useableCouponList.size(), TipCountUtil.BIG_FLAG) + ")");
                        cf.refreshView(useableCouponList, true);
                    } else {
                        List<CouponEntity> unUseableCouponList = datas.getUnUseableCouponList();
                        if (null == unUseableCouponList) {
                            unUseableCouponList = new ArrayList<>();
                        }
                        updateTitle(i, "不可用红包(" + TipCountUtil.cover(unUseableCouponList.size(), TipCountUtil.BIG_FLAG) + ")");
                        cf.refreshView(unUseableCouponList, false);
                    }
                }
            }
        }
    }

    @Override
    protected String[] createTitles() {
        return new String[]{
                CommonUtils.getStringByResId(R.string.dl_dealers_envelop_canuse) + "(0)", CommonUtils.getStringByResId(R.string.dl_dealers_envelop_notuse) + "(0)"
        };
    }

    @Override
    protected Fragment getFragmentByPos(int position) {
        return CouponableFragment.newInstance(position == 0);
    }
}
